#!/usr/bin/env node

// 设置管理员用户的脚本
const { PrismaClient } = require('./prisma/client/index.js')
const bcrypt = require('bcrypt')

const prisma = new PrismaClient()

async function setupAdmin() {
  try {
    console.log('🔧 Setting up admin user...')

    // 查找现有的testdev用户
    const existingUser = await prisma.developer.findUnique({
      where: { email: 'testdev@example.com' }
    })

    if (existingUser) {
      // 将现有用户设置为管理员
      await prisma.developer.update({
        where: { id: existingUser.id },
        data: { 
          role: 'admin',
          verified: true,
          emailVerified: true
        }
      })
      console.log('✅ Updated testdev@example.com to admin role')
    } else {
      console.log('❌ testdev@example.com user not found')
    }

    // 也创建一个专门的管理员用户
    const adminEmail = 'admin@example.com'
    const existingAdmin = await prisma.developer.findUnique({
      where: { email: adminEmail }
    })

    if (!existingAdmin) {
      // 创建管理员用户（密码需要哈希）
      const hashedPassword = await bcrypt.hash('admin123', 10)

      await prisma.developer.create({
        data: {
          username: 'admin',
          email: adminEmail,
          passwordHash: hashedPassword,
          displayName: 'System Administrator',
          role: 'admin',
          status: 'active',
          verified: true,
          emailVerified: true
        }
      })
      console.log('✅ Created admin@example.com with admin role')
    } else {
      // 更新现有管理员
      await prisma.developer.update({
        where: { id: existingAdmin.id },
        data: { 
          role: 'admin',
          verified: true,
          emailVerified: true
        }
      })
      console.log('✅ Updated admin@example.com to admin role')
    }

    console.log('🎉 Admin setup completed!')
  } catch (error) {
    console.error('❌ Error setting up admin:', error)
  } finally {
    await prisma.$disconnect()
  }
}

setupAdmin()
